import Vue from 'vue'
import axios from 'axios'
import 'nprogress/nprogress.css'
import nprogress from 'nprogress'
import {
	router
} from '../router'
import {
	myMessage
} from '../utils/resetMessage'
import {
	getSession,
	clearSession
} from '@/utils/session'

// axios.defaults.baseURL = process.env.VUE_APP_BASEURL
// 打包后修改接口地址
axios.defaults.baseURL =
	process.env.VUE_APP_ENV == 'prod' ? cfg.src : process.env.VUE_APP_BASEURL

axios.interceptors.request.use((config) => {
	nprogress.start()
	config.headers['Authorization'] = getSession('authorization')
	return config
})

axios.interceptors.response.use(response => {
	nprogress.done()
	let { code, msg } = response.data
	if (code == 0 || !code) {
		return response
	} else {
		if (code == 101) {
			//账号重复登录
			clearSession()
			router.replace({ name: 'login' })
			myMessage({ message: msg, type: 'warning' })
		} else if (msg == '用户身份验证失败') {
			router.replace({ name: 'login' })
		} else {
			myMessage({ message: msg, type: 'warning' })
		}
	}
}, err => {
	return Promise.reject(err)
})

export default axios